package com.roc.web.action.estrn;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblActSum;
import com.roc.pojo.TblTfrTrnLog;
import com.roc.pojo.TransSum;
import com.roc.service.IExcelService;
import com.roc.service.YsbTransSumService;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.Utils;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
@Component
@Scope("prototype")
@Namespace("/transSum")
public class YsbTransSumAction extends PaginationBaseAction{

	private static final long serialVersionUID = 8989281717594864770L;
	
	private Logger logger=LogManager.getLogger(YsbTransSumAction.class);
	
	private YsbTransSumSearchCondition searchCondition;
	
	@Autowired
	IPageService pagenitionService;
	
	@Autowired
	private IPowerInfoService powerInfoService;
	
	@Autowired
	private IExcelService excelService;
	
	private InputStream excelFile;
	
	@Action(value = "transSumJspInit", results = { @Result(name = "success", location = "/pages/estrn/queryTransSumList.jsp")
	,@Result(name = "error", location = "/error.jsp")})
	public String transSumJspInit(){
		logger.info("跳转到云商D0交易信息统计查询页面");
        Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
        /*if (!op.getRoleType().equals(Role.AGENT.getCode()) && !op.getRoleType().equals(Role.O_MANAGER.getCode())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}*/
        
        if(searchCondition==null){
			searchCondition=new YsbTransSumSearchCondition();
		}
		
		/*searchCondition.setMinDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
		searchCondition.setMaxDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));*/
		return SUCCESS;
	}
	
	@Action(value = "queryTransSumList", results = { @Result(name = "success", location = "/pages/estrn/queryTransSumList.jsp")
    })
	public String queryTransSumList(){
		logger.info("查询云商宝D0交易信息统计记录");
        Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			if(searchCondition==null){
				searchCondition=(YsbTransSumSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new YsbTransSumSearchCondition();
				}
			}
			Map<String, String> map=powerInfoService.queryRealIdByOpId(logingMerchant.getSuperiorId(), logingMerchant.getRoleType(), logingMerchant.getId(), logingMerchant.getOrgCode());
	        String superRole= map.get("superRole");
	        String opRealId =map.get("opRealId");
	        //当登录人员为代理商时，查询他的子代理
			searchCondition.setRoleType(superRole);
			if(Role.MERCHANT.getCode().equals(superRole)){
				searchCondition.setMerNo(logingMerchant.getAccountNo());
			}else if(Role.AGENT.getCode().equals(superRole)||Role.SFB_AGENT.getCode().equals(superRole)||Role.O_MANAGER.getCode().equals(superRole)){
					
				String agentId= opRealId;
				searchCondition.setAgentId(agentId);
					
			}else if(Role.AGENT_BUSS.getCode().equals(superRole)){
				searchCondition.setOpId(opRealId);
			}else if(Role.MARKET_DIRECT.getCode().equals(superRole) || Role.MARKET_LEAD.getCode().equals(superRole)){
				searchCondition.setMarketorId(opRealId);
			}
			
			int rows = pagenitionService.countSQL(searchCondition);
			
			if(rows>0){
				searchRsList = pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			
			List<TblActSum> transSumList = new ArrayList<TblActSum>();
			dealTheSearchRsList(transSumList,searchRsList);
			getRequest().setAttribute("transSumList", transSumList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		
		return SUCCESS;
	}
	
	@Action(value="exportTransSumList",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xlsx",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/estrn/queryTransSumList.jsp") }) 
	public String exportTransSumList(){
		
		

		logger.info("查询云商宝D0交易信息统计记录");
        Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			if(searchCondition==null){
				searchCondition=(YsbTransSumSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new YsbTransSumSearchCondition();
				}
			}
			Map<String, String> map=powerInfoService.queryRealIdByOpId(logingMerchant.getSuperiorId(), logingMerchant.getRoleType(), logingMerchant.getId(), logingMerchant.getOrgCode());
	        String superRole= map.get("superRole");
	        String opRealId =map.get("opRealId");
	        //当登录人员为代理商时，查询他的子代理
			searchCondition.setRoleType(superRole);
			if(Role.MERCHANT.getCode().equals(superRole)){
				searchCondition.setMerNo(logingMerchant.getAccountNo());
			}else if(Role.AGENT.getCode().equals(superRole)||Role.SFB_AGENT.getCode().equals(superRole)||Role.O_MANAGER.getCode().equals(superRole)){
					
				String agentId= opRealId;
				searchCondition.setAgentId(agentId);
					
			}else if(Role.AGENT_BUSS.getCode().equals(superRole)){
				searchCondition.setOpId(opRealId);
			}else if(Role.MARKET_DIRECT.getCode().equals(superRole) || Role.MARKET_LEAD.getCode().equals(superRole)){
				searchCondition.setMarketorId(opRealId);
			}
			
			int rows = pagenitionService.countSQL(searchCondition);
			
			if(rows>0){
				searchRsList = pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
			}
			
			List<TblActSum> transSumList = new ArrayList<TblActSum>();
			dealTheSearchRsList(transSumList,searchRsList);
			
			logger.info("rows:" + rows + "    searchRsList.size():"
					+ transSumList.size());
			
			SXSSFWorkbook work = excelService.exportTransSumList(
					transSumList, searchCondition.getMinDate(),
					searchCondition.getMaxDate());

			ByteArrayOutputStream output = new ByteArrayOutputStream();
			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);
			output.flush();
			output.close();

			logger.info("导出商户D0交易信息统计结束");
			
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		
		return SUCCESS;
	
	}
	

	private void dealTheSearchRsList(List<TblActSum> transSumList,
			List<Object> searchRsList) {

		try {
	    Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
	    
		if(searchRsList!=null&&searchRsList.size()>0){
			Iterator iterator=searchRsList.iterator();
			while (iterator.hasNext()) {
				Object[] obj= (Object[])iterator.next();
				TblActSum sum = new TblActSum();
				
				sum.setMchtCd(Constance.Null2EmptyTrim(obj[0]));
				
				sum.setNameBusi(Constance.Null2EmptyTrim(obj[2]));
				
				String assetFlag = Constance.Null2EmptyTrim(obj[4]);
				if("0".equals(assetFlag)){
					sum.setAssetFlag("公司直采");//'0':'公司直采','1':'公司代采','2':'携机入网'
				}else if("1".equals(assetFlag)){
					sum.setAssetFlag("公司代采");//'0':'公司直采','1':'公司代采','2':'携机入网'
				}else if("2".equals(assetFlag)){
					sum.setAssetFlag("携机入网");//'0':'公司直采','1':'公司代采','2':'携机入网'
				}else{
					sum.setAssetFlag("未知");//'0':'公司直采','1':'公司代采','2':'携机入网'
				}
				String phNo = Constance.Null2EmptyTrim(obj[1]);
				String certifNo = Constance.Null2EmptyTrim(obj[3]);
				String account = Constance.Null2EmptyTrim(obj[5]);
				if(Role.SYSTEM.getCode().equals(logingMerchant.getRoleType()) || Role.MANAGER.getCode().equals(logingMerchant.getRoleType())
						|| Role.CLEAR_OPERATORS.getCode().equals(logingMerchant.getRoleType()) || Role.CLEAR_LEAD.getCode().equals(logingMerchant.getRoleType())
						||Role.FINANCE_COMM.getCode().equals(logingMerchant.getRoleType()) || Role.FINANCE_LEAD.getCode().equals(logingMerchant.getRoleType())
						||Role.RISK_CONTROL_OPERATORS.getCode().equals(logingMerchant.getRoleType()) || Role.RISK_CONTROL_LEAD.getCode().equals(logingMerchant.getRoleType())){
					sum.setPhNo(phNo);
					sum.setCertifNo(certifNo);
					sum.setAccount(account);
				}else{
					
					sum.setPhNo(phNo.substring(0, 3)+"****"+phNo.substring(phNo.length()-4));
					sum.setCertifNo(certifNo.substring(0, 4)+"****"+certifNo.substring(certifNo.length()-4));
					sum.setAccount(account.substring(0, 4)+"****"+account.substring(account.length()-4));
				}
				
				
				sum.setRemark1(Constance.Null2EmptyTrim(obj[6]));
				sum.setRemark2(Constance.Null2EmptyTrim(obj[7]));
				sum.setTransAt(Constance.Null2EmptyTrim(obj[8]));
				
				String isSuccess = Constance.Null2EmptyTrim(obj[9]);
				if("0".equals(isSuccess)){
					sum.setIsSuccess("活动进行中");//'1':'已满','0':'未满'
				}else if("1".equals(isSuccess)){
					sum.setIsSuccess("已达标");//'1':'已满','0':'未满'
				}else{
					sum.setIsSuccess("未达标");
				}
				
				sum.setBindDate(Constance.Null2EmptyTrim(obj[10]));
				sum.setSerialNum(Constance.Null2EmptyTrim(obj[11]));
				sum.setDesDate(Constance.Null2EmptyTrim(obj[12]));
				sum.setDesAt(Constance.Null2EmptyTrim(obj[13]));
				transSumList.add(sum);
			}
		}
		
		} catch (Exception e) {
			logger.error("云商宝汇总查询List解析异常",e);
			throw new RuntimeException("云商宝汇总List解析异常");
		}
	
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_TRANS_SUM, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (YsbTransSumSearchCondition)getSession().getAttribute(SEARCH_SESSION_TRANS_SUM);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE+"";
	}

	public YsbTransSumSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(YsbTransSumSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}
	
	public String getExcelName() {
		String excelName = "云商宝商户D0交易信息汇总" + Constance.formateDate();

		try {
			excelName = new String(excelName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			// e.printStackTrace();
			logger.info("生成excel名称失败了！");
		}

		return excelName;

	}
	
}
